package com.example.paopao.consumer.account.dao.persist.repository.impl;

import com.example.paopao.consumer.account.dao.persist.mapper.MemberMapper;
import com.example.paopao.consumer.account.dao.persist.mapper.UserAuthorMapper;
import com.example.paopao.consumer.account.dao.persist.mapper.UserMapper;
import com.example.paopao.consumer.account.dao.persist.repository.IUserRepository;
import com.example.paopao.consumer.account.pojo.entity.Author;
import com.example.paopao.consumer.account.pojo.entity.Integrals;
import com.example.paopao.consumer.account.pojo.entity.User;
import com.example.paopao.consumer.account.pojo.entity.UserAuthor;
import com.example.paopao.consumer.account.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserRepositoryImpl implements IUserRepository {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserAuthorMapper userAuthorMapper;

    @Override
    public UserVO selectByName(String name) {
        return userMapper.selectByName(name);
    }

    @Override
    public int insert(User user) {
        List<Author> authors = userAuthorMapper.listAuthor();
         int countUser = userMapper.countUser()+1;
         user.setLimit(Long.valueOf(countUser));

         userMapper.insert(user);

        int start = authors.size() - 4;
        int end=0;
        for (Author author : authors) {
            UserAuthor auth=new UserAuthor();
            auth.setUserId(Long.valueOf(countUser));
            auth.setAuthorId(author.getId());
            userAuthorMapper.insertUserAuthor(auth);
            end++;
            if (end>start){
                break;
            }
        }
        Integrals integrals=new Integrals();
        integrals.setUserId(user.getId());
        integrals.setBalance(0);
        Long memberNum=System.currentTimeMillis();
        integrals.setMemberNum(memberNum.toString());
        memberMapper.setMemberUser(integrals);

        return 1;
    }

    @Override
    public List<UserVO> selectByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }
}
